package com.agritech.facade;

import com.agritech.machine.AgriculturalMachine;
import com.agritech.command.*;
import com.agritech.task.TaskScheduler;
import com.agritech.task.Task;
import com.agritech.environment.EnvironmentMonitoringSystem;
import com.agritech.path.PathPlan;
import com.agritech.path.PathPlanningContext;
import com.agritech.strategy.AStarPathStrategy;
import com.agritech.system.NavigationSystem;

import java.util.List;
import java.util.Map;

/**
 * 农机控制面板外观类
 * 外观模式：为子系统中的一组接口提供一个统一的界面，此接口使得这一子系统更加容易使用
 */
public class ControlPanelFacade {
    private final TaskScheduler taskScheduler;
    private final EnvironmentMonitoringSystem envMonitor;
    private final RemoteControl remoteControl;
    private final PathPlanningContext pathPlanner;
    private final NavigationSystem navigationSystem;
    private final List<AgriculturalMachine> allMachines; // 统一管理所有农机

    public ControlPanelFacade(List<AgriculturalMachine> machines, EnvironmentMonitoringSystem envMonitor) {
        this.allMachines = machines;
        this.taskScheduler = new TaskScheduler(machines);
        this.envMonitor = envMonitor;
        this.remoteControl = new RemoteControl();
        this.pathPlanner = new PathPlanningContext(new AStarPathStrategy()); // 默认A*策略
        this.navigationSystem = NavigationSystem.getInstance();
        System.out.println("农机控制面板已初始化");
    }

    // --- 环境监测相关 --- 
    public void collectAndDisplayEnvironmentData() {
        System.out.println("\n--- 环境数据采集 ---");
        envMonitor.collectData();
        System.out.println("---------------------");
    }

    // --- 农机管理相关 --- 
    public void displayAllMachineStatus() {
        System.out.println("\n--- 所有农机状态 ---");
        if (allMachines.isEmpty()) {
            System.out.println("系统中没有农机设备。");
            return;
        }
        for (AgriculturalMachine machine : allMachines) {
            System.out.println("  农机ID: " + machine.getId() + ", 类型: " + machine.getType() + 
                               ", 状态: " + machine.getStatus() + ", 燃油: " + 
                               String.format("%.1f", machine.getFuelLevel()) + "%");
        }
        System.out.println("---------------------");
    }

    public AgriculturalMachine findMachineById(String id) {
        return allMachines.stream().filter(m -> m.getId().equals(id)).findFirst().orElse(null);
    }

    public void startMachine(String machineId) {
        AgriculturalMachine machine = findMachineById(machineId);
        if (machine != null) {
            Command startCmd = new StartMachineCommand(machine);
            remoteControl.setCommand(startCmd);
            remoteControl.pressButton();
        } else {
            System.out.println("未找到ID为 " + machineId + " 的农机");
        }
    }

    public void stopMachine(String machineId) {
        AgriculturalMachine machine = findMachineById(machineId);
        if (machine != null) {
            Command stopCmd = new StopMachineCommand(machine);
            remoteControl.setCommand(stopCmd);
            remoteControl.pressButton();
        } else {
            System.out.println("未找到ID为 " + machineId + " 的农机");
        }
    }

    // --- 任务管理相关 --- 
    public Task createTask(String name, String description, double duration) {
        return taskScheduler.createTask(name, description, duration);
    }

    public void assignTaskToMachine(Task task, String machineId, PathPlan pathPlan) {
        AgriculturalMachine machine = findMachineById(machineId);
        if (task != null && machine != null) {
            taskScheduler.assignTask(task, machine, pathPlan);
        } else {
            System.out.println("任务分配失败: 任务或农机不存在");
        }
    }
    
    public void autoAssignTasks() {
        taskScheduler.autoAssignTasks();
    }

    public void startScheduledTask(String taskId) {
        taskScheduler.startTask(taskId);
    }

    public void completeScheduledTask(String taskId) {
        taskScheduler.completeTask(taskId);
    }
    
    public void cancelScheduledTask(String taskId) {
        taskScheduler.cancelTask(taskId);
    }

    public void displayAllTaskStatuses() {
        taskScheduler.printAllTaskStatuses();
    }
    
    public void displayTaskDetails(String taskId) {
        taskScheduler.printTaskDetails(taskId);
    }

    // --- 路径规划与导航 --- 
    public PathPlan planPathForMachine(String machineId, double startX, double startY, double endX, double endY, double[][] obstacles) {
        AgriculturalMachine machine = findMachineById(machineId);
        if (machine == null) {
            System.out.println("路径规划失败: 未找到农机 " + machineId);
            return null;
        }
        System.out.println("为农机 " + machine.getType() + " (" + machine.getId() + ") 规划路径...");
        PathPlan plan = pathPlanner.planPath(envMonitor.getEnvironmentData(), startX, startY, endX, endY, obstacles);
        if (plan != null) {
            plan.printPathPlan();
        }
        return plan;
    }

    public void startNavigationForMachine(String machineId, PathPlan plan) {
        AgriculturalMachine machine = findMachineById(machineId);
        if (machine == null || plan == null) {
            System.out.println("导航启动失败: 农机或路径规划无效");
            return;
        }
        System.out.println("启动农机 " + machine.getId() + " 的导航系统...");
        navigationSystem.startNavigation(plan);
        // 实际应用中，导航系统会控制农机移动
        // machine.moveTo(plan.getPathPoints().get(0).getX(), plan.getPathPoints().get(0).getY());
    }

    public void stopNavigationForMachine(String machineId) {
        System.out.println("停止农机 " + machineId + " 的导航...");
        navigationSystem.stopNavigation();
    }
    
    public void setPathPlanningStrategy(com.agritech.strategy.PathPlanningStrategy strategy) {
        pathPlanner.setStrategy(strategy);
    }

    // --- 命令历史 --- 
    public void undoLastMachineCommand() {
        remoteControl.pressUndoButton();
    }
    
    public void viewCommandHistory(int count) {
        remoteControl.viewCommandHistory(count);
    }

    // --- 获取子系统实例，供高级用户或测试使用 ---
    public TaskScheduler getTaskScheduler() { return taskScheduler; }
    public EnvironmentMonitoringSystem getEnvMonitor() { return envMonitor; }
    public RemoteControl getRemoteControl() { return remoteControl; }
    public PathPlanningContext getPathPlanner() { return pathPlanner; }
    public NavigationSystem getNavigationSystem() { return navigationSystem; }
    public List<AgriculturalMachine> getAllMachines() { return allMachines; }
}